/*
 * @Author: biankai
 * @Date: 2021-04-19 18:47:04
 * @LastEditTime: 2021-11-10 11:18:29
 * @LastEditors: biankai
 * @FilePath: /gitee/devops_service/src/common/error.interceptor.ts
 */
import { ExecutionContext, HttpException, Injectable, NestInterceptor, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable()
export class ErrorsInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, calls$: CallHandler): Observable<any> {
        return calls$.handle().pipe(catchError((error, caught) => {
            console.log(error)
            if (error instanceof HttpException) {
                return Promise.resolve({
                    code: error.getStatus(),
                    message: error.getResponse(),
                });
            }
            if (error instanceof TypeError) {
                return Promise.resolve({
                    code: 500,
                    message: error.stack,
                });
            }
            if (error.name === 'HttpError') {
                return Promise.resolve({
                    code: 500,
                    message: error.response.body.message,
                });
            }
            if (error.message.indexOf('jenkins') !== -1) {
                return Promise.resolve({
                    code: 500,
                    message: error.message,
                });
            }
            return Promise.resolve({
                code: 500,
                message: error,
            });
        }));
    }
}